# Copyright 2010 Mikko Rantanen
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import fuse
import stat
import os
import logging
from time import time

from channelfile import ChannelFile

class CommBus(fuse.Stat):

    def __init__(self, message_cb = None):
        assert message_cb, "Message callback must be specified"
        # Directories have two links. Itself and the previous one.
        self.st_nlink = 2

        # Kinda default directory size.
        self.st_size = 4096

        # Temporary till we figure out smarter defaults.
        self.st_mode = stat.S_IFDIR | 0755
        self.st_ino = 0
        self.st_dev = 0
        self.st_uid = os.getuid()
        self.st_gid = os.getgid()
        self.st_atime = int(time())
        self.st_mtime = self.st_atime
        self.st_ctime = self.st_atime

        self.channels = {}
        self.message_cb = message_cb

    def get_contents(self):
        class contentProxy():
            def __init__(self, name):
                self.name = name
            def get_name(self):
                return self.name

        return [ contentProxy("test") ]

    def channel(self, path):
        if path not in self.channels:
            self.channels[path] = ChannelFile(
                path, 
                destroy_cb = lambda channel : self.remove_channel(channel),
                message_cb = lambda cmd, arg : self.message_cb(cmd, arg))

        return self.channels[path]

    def remove_channel(self, channel):
        del self.channels[channel.name]

